import requests
import json
import time

# 配置
BASE_URL = "http://127.0.0.1:5000"
TEST_USER = {
    "username": f"testuser_{int(time.time())}",  # 使用时间戳确保用户名唯一
    "email": f"test{int(time.time())}@example.com",
    "password": "123456",
    "full_name": "测试用户",           # 字符串 - 非必填
    "age": 25,                        # 整数 - 非必填
    "gender": "male",                 # 字符串 - 非必填 (male/female/other)
    "height": 175.5,                  # 浮点数 - 非必填 (单位: cm)
    "weight": 70.0                    # 浮点数 - 非必填 (单位: kg)
}

class HealthMonitorTester:
    def __init__(self, base_url):
        self.base_url = base_url
        self.token = None
        self.user_id = None
    
    def print_separator(self, title):
        print(f"\n{'='*50}")
        print(f" {title} ")
        print(f"{'='*50}")
    
    def print_request_info(self, method, endpoint, data=None):
        print(f"\n📤 请求: {method} {endpoint}")
        if data:
            print(f"📦 请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
    
    def print_response_info(self, response):
        print(f"📥 响应状态码: {response.status_code}")
        try:
            response_data = response.json()
            print(f"📦 响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
            return response_data
        except:
            print(f"📦 响应内容: {response.text}")
            return None
    
    def test_register(self):
        """测试用户注册"""
        self.print_separator("1. 用户注册测试")
        
        endpoint = f"{self.base_url}/api/auth/register"
        self.print_request_info("POST", "/api/auth/register", TEST_USER)
        
        # 测试必填字段验证
        print("\n--- 测试必填字段验证 ---")
        missing_data = {"username": "test"}  # 缺少email和password
        response = requests.post(endpoint, json=missing_data)
        self.print_response_info(response)
        
        # 正常注册
        print("\n--- 正常注册测试 ---")
        response = requests.post(endpoint, json=TEST_USER)
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            self.token = response_data.get('access_token')
            self.user_id = response_data.get('user', {}).get('id')
            print(f"✅ 注册成功 - 用户ID: {self.user_id}")
            return True
        else:
            print("❌ 注册失败")
            return False
    
    def test_login(self):
        """测试用户登录"""
        self.print_separator("2. 用户登录测试")
        
        endpoint = f"{self.base_url}/api/auth/login"
        
        # 测试错误密码
        print("--- 测试错误密码 ---")
        wrong_data = {
            "username": TEST_USER["username"],
            "password": "wrongpassword"
        }
        self.print_request_info("POST", "/api/auth/login", wrong_data)
        response = requests.post(endpoint, json=wrong_data)
        self.print_response_info(response)
        
        # 正常登录
        print("\n--- 正常登录测试 ---")
        login_data = {
            "username": TEST_USER["username"],
            "password": TEST_USER["password"]
        }
        self.print_request_info("POST", "/api/auth/login", login_data)
        response = requests.post(endpoint, json=login_data)
        response_data = self.print_response_info(response)
        
        if response.status_code == 200:
            self.token = response_data.get('access_token')
            print("✅ 登录成功")
            return True
        else:
            print("❌ 登录失败")
            return False
    
    def test_get_current_user(self):
        """测试获取当前用户信息"""
        self.print_separator("3. 获取当前用户信息")
        
        endpoint = f"{self.base_url}/api/auth/me"
        
        # 测试无token访问
        print("--- 测试无token访问 ---")
        response = requests.get(endpoint)
        self.print_response_info(response)
        
        # 正常获取用户信息
        print("\n--- 正常获取用户信息 ---")
        headers = {"Authorization": f"Bearer {self.token}"}
        self.print_request_info("GET", "/api/auth/me")
        response = requests.get(endpoint, headers=headers)
        response_data = self.print_response_info(response)
        
        if response.status_code == 200:
            print("✅ 获取用户信息成功")
            return True
        else:
            print("❌ 获取用户信息失败")
            return False
    
    def test_get_profile(self):
        """测试获取用户资料"""
        self.print_separator("4. 获取用户资料")
        
        endpoint = f"{self.base_url}/api/user/profile"
        headers = {"Authorization": f"Bearer {self.token}"}
        
        self.print_request_info("GET", "/api/user/profile")
        response = requests.get(endpoint, headers=headers)
        response_data = self.print_response_info(response)
        
        if response.status_code == 200:
            print("✅ 获取用户资料成功")
            return True
        else:
            print("❌ 获取用户资料失败")
            return False
    
    def test_update_profile(self):
        """测试更新用户资料"""
        self.print_separator("5. 更新用户资料")
        
        endpoint = f"{self.base_url}/api/user/profile"
        headers = {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json"
        }
        
        # 更新数据 - 测试不同类型字段
        update_data = {
            "full_name": "更新后的用户名",  # 字符串
            "age": 26,                    # 整数
            "gender": "female",           # 字符串
            "height": 176.2,              # 浮点数
            "weight": 68.5                # 浮点数
        }
        
        self.print_request_info("PUT", "/api/user/profile", update_data)
        response = requests.put(endpoint, json=update_data, headers=headers)
        response_data = self.print_response_info(response)
        
        if response.status_code == 200:
            print("✅ 更新用户资料成功")
            
            # 验证更新结果
            print("\n--- 验证更新结果 ---")
            get_response = requests.get(endpoint, headers=headers)
            updated_data = get_response.json()
            user_data = updated_data.get('user', {})
            
            # 检查字段是否更新成功
            updates_successful = True
            for key, expected_value in update_data.items():
                actual_value = user_data.get(key)
                if actual_value != expected_value:
                    print(f"❌ 字段 {key} 更新失败: 期望 {expected_value}, 实际 {actual_value}")
                    updates_successful = False
                else:
                    print(f"✅ 字段 {key} 更新成功: {actual_value}")
            
            return updates_successful
        else:
            print("❌ 更新用户资料失败")
            return False
    
    def test_logout(self):
        """测试用户退出"""
        self.print_separator("6. 用户退出")
        
        endpoint = f"{self.base_url}/api/auth/logout"
        headers = {"Authorization": f"Bearer {self.token}"}
        
        self.print_request_info("POST", "/api/auth/logout")
        response = requests.post(endpoint, headers=headers)
        response_data = self.print_response_info(response)
        
        if response.status_code == 200:
            print("✅ 退出成功")
            
            # 测试退出后访问受保护接口
            print("\n--- 测试退出后访问受保护接口 ---")
            test_response = requests.get(f"{self.base_url}/api/auth/me", headers=headers)
            if test_response.status_code == 401:
                print("✅ Token已失效，退出成功")
            else:
                print("⚠️ Token可能仍然有效")
            
            return True
        else:
            print("❌ 退出失败")
            return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print("🚀 开始健康检测系统API测试")
        print(f"📝 测试用户: {TEST_USER['username']}")
        
        tests = [
            self.test_register,
            self.test_login,
            self.test_get_current_user,
            self.test_get_profile,
            self.test_update_profile,
            self.test_logout
        ]
        
        passed_tests = 0
        total_tests = len(tests)
        
        for test in tests:
            try:
                if test():
                    passed_tests += 1
            except Exception as e:
                print(f"❌ 测试执行出错: {e}")
        
        # 测试总结
        self.print_separator("测试总结")
        print(f"📊 总测试数: {total_tests}")
        print(f"✅ 通过: {passed_tests}")
        print(f"❌ 失败: {total_tests - passed_tests}")
        print(f"📈 通过率: {passed_tests/total_tests*100:.1f}%")
        
        if passed_tests == total_tests:
            print("🎉 所有测试通过！")
        else:
            print("💡 部分测试失败，请检查API实现")

if __name__ == "__main__":
    # 创建测试实例并运行
    tester = HealthMonitorTester(BASE_URL)
    tester.run_all_tests()